package com.wisdytech.app.produceExecute.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wisdytech.app.produceExecute.common.bean.ParamMq;
import com.wisdytech.common.bean.EquipDataDto;
import com.wisdytech.common.bean.ParamDataDto;
import com.wisdytech.common.bean.StandardMsgResult;
import com.wisdytech.common.bean.event.MesParamChangeEvent;
import com.wisdytech.linkdcs.account.dao.TtEqEquipmentAidDao;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wisdytech.linkdcs.account.model.TtEqEquipmentAid;
import javax.annotation.Resource;

import com.wisdytech.linkdcs.ieMaintenance.dao.IeMaintenanceDao;
import com.wisdytech.linkdcs.ieMaintenance.model.IeMaintenance;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.github.pagehelper.PageInfo;
import com.wisdytech.app.produceExecute.common.ChangeFilterUtil;
import com.wisdytech.app.produceExecute.common.FilterMes;
import com.wisdytech.app.produceExecute.common.HisDataDto;
import com.wisdytech.app.produceExecute.dto.EquipDataSearchDTO;
import com.wisdytech.app.produceExecute.service.EqProduceService;
import com.wisdytech.app.produceExecute.vo.CollectParamVO;
import com.wisdytech.app.produceExecute.vo.EqAccountVO;
import com.wisdytech.app.produceExecute.vo.EquipModelVO;
import com.wisdytech.app.produceExecute.vo.EquipParamVO;
import com.wisdytech.app.produceExecute.vo.EquipRealDataVO;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.thrift.service.ThriftClient;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.account.dao.TtEqAccountDao;
import com.wisdytech.linkdcs.account.model.TtEqAccount;
import com.wisdytech.linkdcs.equipment.dao.IEqCollectionParamDao;
import com.wisdytech.linkdcs.equipment.dao.IEqModelDao;
import com.wisdytech.linkdcs.equipment.model.CollectionParam;
import com.wisdytech.linkdcs.equipment.service.impl.EquipmentDataServiceImpl;
@Service("eqProduceService")
@Transactional(readOnly=true)
public class EqProduceServiceImpl extends BaseService<TtEqAccountDao,TtEqAccount> implements EqProduceService{

    private static Logger logger =LoggerFactory.getLogger(EquipmentDataServiceImpl.class);
    @Resource
    private IeMaintenanceDao ieMaintenanceDao;
    @Resource
    ThriftClient thriftClient;

    /**restful服务*/
    @Autowired
    private RestTemplate restTemplate;

    /**主地址*/
    @Value("${restful.baseUrl}")
    private String baseUrl;
    /**
     * 注入eqCollectionParamDao
     */
    @Resource
    private IEqCollectionParamDao eqCollectionParamDao;
    @Resource
    private TtEqAccountDao ttEqAccountDao;
    @Resource
    private TtEqEquipmentAidDao ttEqEquipmentAidDao;

    @Autowired
    private AmqpTemplate rabbitTemplate;

    /**队列名称*/
    /**工序参数*/
    @Value("${mqQueue.op}")
    private String opParam;
    /**区域参数*/
    @Value("${mqQueue.area}")
    private String areaParam;

    @Override
    public PageInfo<EqAccountVO> listEquipByLineAndOp(String equipCode,String lineCode, String opCode, String shopCode, String areaCode, String equipCodeOrName,
                                                      String equipId, String status, String unStatus, String realStatus, String equipType) {
        Map<String, Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(equipCode)) {
            params.put("equipCode",equipCode);
        }
        if(StringUtils.isNotBlank(lineCode)) {
            params.put("lineCode",lineCode);
        }
        if(StringUtils.isNotBlank(opCode)) {
            params.put("opCode",opCode);
        }
        if(StringUtils.isNotBlank(shopCode)) {
            params.put("shopCode",shopCode);
        }
        if(StringUtils.isNotBlank(areaCode)) {
            params.put("areaCode",areaCode);
        }
        if(StringUtils.isNotBlank(equipCodeOrName) && !equipCodeOrName.equals("null")) {
            params.put("equipCodeOrName",equipCodeOrName);
        }
        if(StringUtils.isNotBlank(equipId)) {
            params.put("equipId",equipId);
        }
        if(StringUtils.isNotBlank(status)) {
            params.put("status",status);
        }
        if(StringUtils.isNotBlank(unStatus)) {
            params.put("unStatus",unStatus);
        }
        if(StringUtils.isNotBlank(realStatus)) {
            params.put("realStatus",realStatus);
        }
        if(StringUtils.isNotBlank(equipType)) {
            params.put("equipType",equipType);
        }

        List<EqAccountVO> list = ttEqAccountDao.listEquipByLineAndOp(params);
        //获取辅助设备编码
        for(EqAccountVO EqAccountVO : list) {
            List<EqAccountVO> listAid = ttEqAccountDao.listEquipAidByEqCode(EqAccountVO.getEquipCode());
            List<String> aidList = new ArrayList<>();
            if(!listAid.isEmpty()) {
                for(EqAccountVO EqAidVO : listAid) {
                    if(EqAccountVO.getEquipCode().equals(EqAidVO.getEquipCode())) {
                        aidList.add(EqAidVO.getEquipCode());
                    }
                }
                String aidEqCode = aidList.toString();
                String aidEqCodeReal = aidEqCode.substring(1, aidEqCode.lastIndexOf("]"));
                EqAccountVO.setAuxiliaryEquipCode(aidEqCodeReal);
            }

        }
        PageInfo<EqAccountVO> page = new PageInfo<>(list);
        return page;
    }

    @SuppressWarnings("unchecked")
    @Override
    public PageInfo<EquipRealDataVO> listHistoryDetail(EquipDataSearchDTO dto) {
        //查询的实时数据列表
        List<EquipRealDataVO> eqDataList =new ArrayList<>();
        PageInfo<EquipRealDataVO> page = new PageInfo<>(eqDataList);
        //设备id和参数不能为空
        if(StringUtils.isBlank(dto.getEquipCode())|| StringUtils.isBlank(dto.getCollectItemId())){
            return page;
        }
        CollectionParam c = this.eqCollectionParamDao.selectById(dto.getCollectItemId());
        if(c==null){
            return null;
        }
        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long l1 = 0;
        long l2 = 0;
        try {
            String start=dto.getStartTime();
            l1 = Long.valueOf(start);
            String end=dto.getEndTime();
            l2 =Long.valueOf(end);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(baseUrl+"/equipment/getEquipHisData?"
                + "equipCode="+dto.getEquipCode()
                + "&paramId="+dto.getCollectItemId()
                + "&paramCode="+c.getParamCode()
                + "&startTime="+l1
                + "&endTime="+l2
                + "&order="+0
                + "&num="+dto.getNum()
                + "&size=" +1000000);
        String dataS =  restTemplate.getForObject(baseUrl+"/equipment/getEquipHisData?"
                        + "equipCode="+dto.getEquipCode()
                        + "&paramId="+dto.getCollectItemId()
                        + "&paramCode="+c.getParamCode()
                        + "&startTime="+l1
                        + "&endTime="+l2
                        + "&order="+0
                        + "&num="+dto.getNum()
                        + "&size=" +1000000
                , String.class);
        StandardMsgResult<HisDataDto<EquipDataDto>> msgResult =JSON.parseObject(dataS, new TypeReference<StandardMsgResult<HisDataDto<EquipDataDto>>>() {});
        HisDataDto<EquipDataDto> hisDataDto =  msgResult.getData();
        List<EquipDataDto> list= hisDataDto.getRows();
        //循环补充返回数据
        for(EquipDataDto eqDatadto : list) {
            EquipRealDataVO vo =new EquipRealDataVO();
            vo.setTime(new Date(eqDatadto.getTime()));
            List<ParamDataDto> paramList = eqDatadto.getParamDatas();
            if(paramList.isEmpty()) {
                vo.setParamValue(null);
            }else {
                vo.setParamValue(paramList.get(0).getValue());
            }
            eqDataList.add(vo);
        }
        return page;
    }

    @Override
    public PageInfo<EqAccountVO> listEqProduceByModelCode(String equipModelCode,String opCode, FilterMes filterMes) {

        List<EqAccountVO> list = ttEqAccountDao.listEqProduceByModelCode(equipModelCode,opCode);
        PageInfo<EqAccountVO> page = new PageInfo<>(list);
        return page;
    }

    @Override
    public List<CollectionParam> getEuipmentParamView(String equipCode) {
        List<CollectionParam> params =new ArrayList<CollectionParam>();
        //设备id 不能为空
        if(StringUtils.isBlank(equipCode)){
            return params;
        }
        params =eqCollectionParamDao.selectEnvironmentParam(equipCode);
        return params;
    }

    @Override
    public List<EquipParamVO> listRealData(String equipCode, List<CollectionParam> params) {

        List<EquipParamVO> list = new ArrayList<>();
        StringBuilder sb =new StringBuilder();
        for(CollectionParam cp : params){
            sb.append(cp.getParamCode()).append(",");
        }
        String param="";
        if(StringUtils.isNotEmpty(sb.toString())){
            param = sb.toString().substring(0,sb.toString().length()-1);
        }

        //获取数据
        String dataS= restTemplate.getForObject(baseUrl+"/equipment/getEquipRealData?code="+equipCode
                + "&params="+param, String.class);
        StandardMsgResult<EquipDataDto> msgResult =JSON.parseObject(dataS, new TypeReference<StandardMsgResult<EquipDataDto>>() {});
        EquipDataDto eqDataDto = msgResult.getData();
        for(CollectionParam cParam : params) {
            EquipParamVO vo = new EquipParamVO();
            vo.setParamName(cParam.getParamName());
            if(!eqDataDto.getParamDatas().isEmpty()){
                if (null != eqDataDto.getParamDatas().get(0).getValue()) {
                    vo.setParamValue(eqDataDto.getParamDatas().get(0).getValue());
                } else {
                    vo.setParamValue("0.00");
                }
            }
            list.add(vo);

        }
        return list;
    }

    @Override
    public List<CollectParamVO> getCollectionParamByEqCode(String equipCode,  String paramType,FilterMes filterMes) {
        List<String> typeList = new ArrayList<String>();
        if(!paramType.isEmpty()) {
            String[] id = paramType.split(",");
            for (int i = 0; i < id.length; i++) {
                typeList.add(id[i]);
            }
        }
        Map<String,Object> param = new HashMap<>();
        param.put("equipCode", equipCode);
        param.put("typeList", typeList);
        //所以设备
        List<CollectParamVO> list = new ArrayList<>();
        //获取生产类参数
        List<CollectParamVO> params = eqCollectionParamDao.getCollectionParamByEqCode(param);
        //判断为主设备
        if(!params.isEmpty()) {
            for(CollectParamVO paramVO : params) {
                paramVO.setIsMainEquip("1");
                list.add(paramVO);
            }
        }
        //获取其辅助类设备
        List<TtEqEquipmentAid> eqList = ttEqEquipmentAidDao.selectAids(equipCode);
        //获取辅助类设备参数
        if(!eqList.isEmpty()) {
            for(TtEqEquipmentAid aid :eqList) {
                Map<String,Object> param1 = new HashMap<>();
                param1.put("equipCode", aid.getAidEquipCode());
                param1.put("typeList", typeList);
                List<CollectParamVO> paramAids = eqCollectionParamDao.getCollectionParamByEqCode(param1);
                //判断为辅助设备
                if(!paramAids.isEmpty()) {
                    for(CollectParamVO vo : paramAids) {
                        vo.setIsMainEquip("0");
                        list.add(vo);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<EquipModelVO> getEquipModelByopCode(String opCode, String modelType, FilterMes filterMes) {
        Filter filter = ChangeFilterUtil.getFilter(filterMes);
        List<EquipModelVO> eqModel = this.beforeList(IEqModelDao.class,filter).getEquipModelByopCode(opCode,modelType);
        return eqModel;
    }

    @Override
    public IeMaintenance getIeMaintenanceByEqCAndProC(String equipCode, String productCode) {
        IeMaintenance ieMaintenance = new IeMaintenance();
        ieMaintenance.setDelFlag("0");
        ieMaintenance.setEquipCode(equipCode);
        ieMaintenance.setProductCode(productCode);
        return this.ieMaintenanceDao.selectOne(ieMaintenance);
    }


    @EventListener
    protected void 	paramEventListener(MesParamChangeEvent event) {
        int type = event.getOperateType().getCode();
        ParamMq mq = event.getParam();
        mq.setOperateType(type);
        switch(Integer.parseInt(mq.getParamType())) {
            case 1:
                rabbitTemplate.convertAndSend(opParam, JSON.toJSONString(mq));
                break;
            case 2:
                rabbitTemplate.convertAndSend(opParam, JSON.toJSONString(mq));
                break;
            case 3:
                rabbitTemplate.convertAndSend(areaParam, JSON.toJSONString(mq));
                break;
            default:
                logger.warn("发送参数数据异常 ！！ ！",type, JSON.toJSONString(mq));
                break;
        }
    }
}
